package image

import (
	"context"
	"os"
	"path/filepath"

	"gitee.com/mkwchecking/sr-admin/pkg/ffmpeg"
	"gitee.com/mkwchecking/sr-admin/pkg/ffmpeg/transcoder"
	"gitee.com/mkwchecking/sr-admin/pkg/file/utils"
)

func NewImageHandlerCustom(ffmpcli *ffmpeg.FFMpeg) *ImageHandler {
	return &ImageHandler{
		ffmpegCli: ffmpcli,
	}
}

func NewImageHandler(ffmpegCli *ffmpeg.FFMpeg) *ImageHandler {
	return &ImageHandler{
		ffmpegCli: ffmpegCli,
	}
}

type ImageHandler struct {
	ffmpegCli *ffmpeg.FFMpeg
}

// func (i *ImageHandler) GenPreview(ctx context.Context, srcPath, output string) error {
// 	ft := visit.ParseFileType(srcPath)
// 	if ft != visit.FileTypeImage && ft != visit.FileTypeVideo {
// 		return fmt.Errorf("unsupported file type %s for imageHandler", filepath.Ext(srcPath))
// 	}

// 	return nil
// }

func (v *ImageHandler) GenCover(ctx context.Context, srcPath, output string) error {
	return v.genViewCover(ctx, srcPath, output)
}

func (v *ImageHandler) GenCoverToTarget(ctx context.Context, srcPath, output string) error {
	return v.genViewCover(ctx, srcPath, output)
}

func (v *ImageHandler) genViewCover(ctx context.Context, path, output string) error {

	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer f.Close()

	outDir := filepath.Dir(output)
	if err = os.MkdirAll(outDir, os.ModePerm); err != nil {
		return err
	}

	out, err := os.Create(output)
	if err != nil {
		return err
	}
	defer out.Close()

	args := transcoder.ImageThumbnail("-", transcoder.ImageThumbnailOptions{
		OutputFormat:  ffmpeg.ImageFormatJpeg,
		OutputPath:    "-",
		MaxDimensions: utils.ScenePreviewWidth,
		Quality:       utils.FFMpegImageQuality,
	})

	res, err := v.ffmpegCli.GenerateOutput(ctx, args, f)
	if err != nil {
		return err
	}
	_, err = out.Write(res)
	return err
}
